<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>校园二手市场 - 消息中心</title>
    <style>
        :root {
            --primary-color: #4CAF50;
            --secondary-color: #66BB6A;
            --light-gray: #F5F5F5;
            --text-color: #212121;
            --sub-text: #757575;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
        }

        body {
            line-height: 1.6;
            color: var(--text-color);
            background-color: var(--light-gray);
            min-height: 100vh;
            padding-bottom: 60px;
            position: relative;
        }

        .header {
            background-color: var(--primary-color);
            color: white;
            padding: 1.2rem;
            text-align: center;
            position: relative;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            z-index: 100;
        }

        .back-btn {
            position: absolute;
            left: 1rem;
            top: 50%;
            transform: translateY(-50%);
            color: white;
            text-decoration: none;
            font-size: 1.2rem;
            padding: 0.5rem;
            border-radius: 4px;
            transition: background-color 0.3s;
            display: flex;
            align-items: center;
        }

        .back-btn::before {
            content: "←";
            font-size: 1.2rem;
        }

        .back-btn:hover {
            background-color: rgba(255, 255, 255, 0.2);
        }

        .content {
            margin: 0 auto;
            padding: 1rem;
        }

        .message-tabs {
            display: flex;
            background-color: white;
            justify-content: space-around;
            border-radius: 12px;
            overflow-x: auto;
            margin: 1rem 0;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
        }

        .message-tab {
            padding: 1rem 1.5rem;
            text-align: center;
            cursor: pointer;
            color: var(--sub-text);
            font-weight: 500;
            white-space: nowrap;
            flex-shrink: 0;
            position: relative;
            transition: color 0.3s;
            display: flex;
            align-items: center;
            gap: 0.3rem;
        }

        .message-tab.active {
            color: var(--primary-color);
        }

        .message-tab.active::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 60%;
            height: 3px;
            background-color: var(--primary-color);
            border-radius: 3px;
        }

        .badge {
            background-color: #ff4d4f;
            color: white;
            border-radius: 10px;
            font-size: 0.6rem;
            padding: 0.1rem 0.4rem;
            min-width: 16px;
            height: 16px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .messages {
            background-color: white;
            border-radius: 12px;
            padding: 1rem;
            margin-bottom: 1rem;
            display: none;
        }

        .messages.active {
            display: block;
        }

        .message-item {
            padding: 1rem;
            margin: 0.5rem 0;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
            border: 1px solid transparent;
        }

        .message-item:hover {
            background-color: #f8f8f8;
            border-color: #eee;
        }

        .message-item.unread {
            background-color: rgba(76, 175, 80, 0.05);
            border-color: rgba(76, 175, 80, 0.2);
        }

        .message-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .message-title {
            font-weight: 500;
            color: var(--text-color);
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .message-time {
            font-size: 0.8rem;
            color: var(--sub-text);
        }

        .message-content {
            font-size: 0.9rem;
            color: var(--sub-text);
            margin-top: 0.3rem;
            line-height: 1.5;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        .message-detail-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: none;
            justify-content: flex-end;
            padding: 1rem;
            backdrop-filter: blur(5px);
            z-index: 101;
            overflow-y: auto;
            padding-bottom: 60px;
        }

        .message-detail-content {
            background-color: white;
            width: 100%;
            border-radius: 16px 16px 0 0;
            padding: 1.5rem;
            display: flex;
            flex-direction: column;
            gap: 1rem;
            position: relative;
            max-height: calc(100vh - 60px);
        }

        .close-btn {
            position: absolute;
            right: 1rem;
            top: 1rem;
            background: none;
            border: none;
            font-size: 1.5rem;
            cursor: pointer;
            color: #999;
            padding: 0.5rem;
            border-radius: 4px;
            transition: background-color 0.3s;
        }

        .close-btn:hover {
            background-color: #f0f0f0;
        }

        .reply-section {
            margin-top: auto;
            display: flex;
            gap: 1rem;
            padding-top: 1rem;
            border-top: 1px solid #eee;
        }

        .reply-input {
            flex: 1;
            padding: 0.8rem;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 1rem;
            outline: none;
            transition: border-color 0.3s;
            min-height: 44px;
        }

        .reply-input:focus {
            border-color: var(--primary-color);
        }

        .send-btn {
            background-color: var(--primary-color);
            color: white;
            border: none;
            padding: 0 1.5rem;
            border-radius: 8px;
            cursor: pointer;
            transition: background-color 0.3s;
            white-space: nowrap;
            min-height: 44px;
            display: flex;
            align-items: center;
        }

        .send-btn:hover {
            background-color: var(--secondary-color);
        }

        .message-bubble-container {
            display: flex;
            flex-direction: column;
            gap: 1rem;
            overflow-y: auto;
            padding-right: 0.5rem;
            margin-bottom: 1rem;
        }

        .message-bubble {
            padding: 0.8rem 1rem;
            border-radius: 0 12px 12px 12px;
            max-width: 70%;
            line-height: 1.5;
            position: relative;
            animation: fadeIn 0.3s ease;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateX(10px); }
            to { opacity: 1; transform: translateX(0); }
        }

        .message-bubble.received {
            background-color: #E8F5E9;
            margin-right: auto;
            border-radius: 0 12px 12px 12px;
        }

        .message-bubble.sent {
            background-color: var(--primary-color);
            color: white;
            margin-left: auto;
            border-radius: 12px 0 12px 12px;
        }

        .message-time-small {
            font-size: 0.7rem;
            color: var(--sub-text);
            margin-top: 0.3rem;
            text-align: right;
        }

        .no-messages {
            text-align: center;
            padding: 2rem;
            color: #999;
            font-size: 0.9rem;
        }

        .nav-bar {
            display: flex;
            justify-content: space-around;
            background-color: #fff;
            padding: 0.5rem;
            position: fixed;
            bottom: 0;
            width: 100%;
            margin: 0 auto;
            left: 50%;
            transform: translateX(-50%);
            box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
            border-radius: 12px 12px 0 0;
            z-index: 102;
        }

        .nav-bar a {
            color: var(--sub-text);
            text-decoration: none;
            padding: 0.5rem 1rem;
            display: flex;
            flex-direction: column;
            align-items: center;
            font-size: 0.8rem;
            transition: color 0.3s;
            position: relative;
        }

        .nav-bar a.active {
            color: var(--primary-color);
        }

        .nav-bar a.active::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 60%;
            height: 3px;
            background-color: var(--primary-color);
            border-radius: 3px;
        }

        .nav-icon {
            width: 24px;
            height: 24px;
            position: relative;
            margin-bottom: 0.2rem;
        }

        .home-icon::before { content: "🏠"; }
        .products-icon::before { content: "📦"; }
        .publish-icon::before { content: "✏️"; }
        .news-icon::before { content: "💬"; }
        .account-icon::before { content: "👤"; }
    </style>
</head>
<body>
    <header class="header">
        <a href="index.html" class="back-btn"></a>
        <h1>消息中心</h1>
    </header>

    <div class="content">
        <div class="message-tabs">
            <div class="message-tab active" data-tab="all">
                全部消息
                <span class="badge">3</span>
            </div>
            <div class="message-tab" data-tab="unread">
                未读消息
                <span class="badge">2</span>
            </div>
            <div class="message-tab" data-tab="system">
                系统消息
                <span class="badge">1</span>
            </div>
            <div class="message-tab" data-tab="transaction">
                交易消息
                <span class="badge">1</span>
            </div>
            <div class="message-tab" data-tab="consult">
                咨询消息
                <span class="badge">1</span>
            </div>
        </div>

        <div class="messages active" id="all-messages"></div>
        <div class="messages" id="unread-messages"></div>
        <div class="messages" id="system-messages"></div>
        <div class="messages" id="transaction-messages"></div>
        <div class="messages" id="consult-messages"></div>
    </div>

    <div class="message-detail-modal" id="messageDetailModal">
        <div class="message-detail-content">
            <button class="close-btn" id="closeDetailModal">×</button>
            <div class="message-detail-header">
                <div class="message-detail-title" id="detailTitle"></div>
                <div class="message-detail-time" id="detailTime"></div>
            </div>
            <div class="message-bubble-container" id="messageBubbleContainer"></div>
            <div class="reply-section">
                <input type="text" class="reply-input" id="replyInput" placeholder="输入回复...">
                <button class="send-btn" id="sendBtn">发送</button>
            </div>
        </div>
    </div>

    <nav class="nav-bar">
        <a href="index.html">
            <div class="nav-icon home-icon"></div>
            首页
        </a>
        <a href="products.html">
            <div class="nav-icon products-icon"></div>
            商品
        </a>
        <a href="publish.html">
            <div class="nav-icon publish-icon"></div>
            发布
        </a>
        <a href="news.html" class="active">
            <div class="nav-icon news-icon"></div>
            消息
        </a>
        <a href="account.html">
            <div class="nav-icon account-icon"></div>
            我的
        </a>
    </nav>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const messages = [
                {
                    id: 1,
                    type: 'system',
                    title: '欢迎使用校园二手市场',
                    content: '尊敬的校园用户，欢迎使用校园二手市场平台！在这里您可以买卖各种二手物品，享受便捷的校园交易服务。如有任何问题，请联系客服。',
                    time: '2023-05-10 09:15:22',
                    isRead: true,
                    replies: []
                },
                {
                    id: 2,
                    type: 'consult',
                    title: '关于您发布的《高等数学》教材',
                    content: '您好，我看到您发布的《高等数学》教材，想了解一下书的版本和使用情况。请问这本书是哪个出版社的？有没有笔记或划线？价格是否可以优惠？期待您的回复。',
                    time: '2023-05-12 14:30:25',
                    isRead: false,
                    replies: [
                        {
                            sender: 'seller',
                            content: '您好，这本书是清华大学出版社的，没有笔记，价格可以优惠到15元。',
                            time: '2023-05-12 15:00:00'
                        }
                    ]
                },
                {
                    id: 3,
                    type: 'transaction',
                    title: '您的订单已支付',
                    content: '您购买的二手自行车（订单号：20230515123456）已支付成功，卖家将在24小时内与您联系确认交易细节。如有任何问题，请联系客服。',
                    time: '2023-05-15 10:45:18',
                    isRead: false,
                    replies: []
                },
                {
                    id: 4,
                    type: 'system',
                    title: '平台维护通知',
                    content: '亲爱的用户，为了提供更好的服务，我们将在5月20日凌晨1:00-3:00进行系统维护，届时平台将暂时无法使用。给您带来的不便，敬请谅解。',
                    time: '2023-05-18 18:20:10',
                    isRead: true,
                    replies: []
                },
                {
                    id: 5,
                    type: 'transaction',
                    title: '您的商品已售出',
                    content: '您发布的《大学英语四级真题》已售出，买家已付款。请尽快与买家联系，约定取货时间和地点。交易金额将在买家确认收货后到账。',
                    time: '2023-05-20 16:05:33',
                    isRead: false,
                    replies: []
                },
                {
                    id: 6,
                    type: 'consult',
                    title: '询问台灯是否还在',
                    content: '您好，我看到您发布的台灯还在售吗？灯光明亮吗？有没有损坏？我住在12号楼，如果方便的话，可以送到楼下吗？谢谢！',
                    time: '2023-05-22 08:45:12',
                    isRead: true,
                    replies: []
                }
            ];

            const tabs = document.querySelectorAll('.message-tab');
            const messageLists = document.querySelectorAll('.messages');
            const messageDetailModal = document.getElementById('messageDetailModal');
            const closeDetailModal = document.getElementById('closeDetailModal');
            const detailTitle = document.getElementById('detailTitle');
            const detailTime = document.getElementById('detailTime');
            const messageBubbleContainer = document.getElementById('messageBubbleContainer');
            const replyInput = document.getElementById('replyInput');
            const sendBtn = document.getElementById('sendBtn');

            let selectedMessageId = null;
            let currentConversation = [];

            function initMessages() {
                const filterTypes = {
                    all: () => messages,
                    unread: msg => !msg.isRead,
                    system: msg => msg.type === 'system',
                    transaction: msg => msg.type === 'transaction',
                    consult: msg => msg.type === 'consult'
                };

                tabs.forEach(tab => {
                    const type = tab.dataset.tab;
                    const filteredMessages = messages.filter(filterTypes[type] || (() => true));
                    renderMessageList(type, filteredMessages);
                });

                updateBadges();
            }

            function renderMessageList(type, msgList) {
                const listElement = document.getElementById(`${type}-messages`);
                listElement.innerHTML = '';

                if (msgList.length === 0) {
                    listElement.innerHTML = '<div class="no-messages">暂无消息</div>';
                    return;
                }

                msgList.forEach(message => {
                    const messageElement = document.createElement('div');
                    messageElement.className = `message-item ${!message.isRead ? 'unread' : ''}`;
                    messageElement.dataset.id = message.id;
                    messageElement.innerHTML = `
                        <div class="message-header">
                            <div class="message-title">
                                ${message.title}
                                ${!message.isRead ? '<span class="badge" style="font-size: 0.6rem; height: auto; padding: 0 0.3rem;">新</span>' : ''}
                            </div>
                            <div class="message-time">${formatTime(message.time)}</div>
                        </div>
                        <div class="message-content">${message.content}</div>
                    `;

                    messageElement.addEventListener('click', function() {
                        showMessageDetail(message);
                        if (!message.isRead && type === 'unread') {
                            message.isRead = true;
                            this.classList.remove('unread');
                            this.querySelector('.message-title').innerHTML = message.title;
                            initMessages();
                        }
                    });

                    listElement.appendChild(messageElement);
                });
            }

            function formatTime(timeStr, short = false) {
                const date = new Date(timeStr);
                const now = new Date();
                const diffInHours = Math.floor((now - date) / (1000 * 60 * 60));

                if (short) {
                    return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
                }

                if (diffInHours < 24) {
                    return `今天 ${date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`;
                } else if (diffInHours < 48) {
                    return `昨天 ${date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`;
                } else {
                    return `${date.getMonth() + 1}/${date.getDate()} ${date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`;
                }
            }

            function updateBadges() {
                const counts = {
                    unread: messages.filter(msg => !msg.isRead).length,
                    system: messages.filter(msg => msg.type === 'system').length,
                    transaction: messages.filter(msg => msg.type === 'transaction').length,
                    consult: messages.filter(msg => msg.type === 'consult').length
                };

                tabs.forEach(tab => {
                    const type = tab.dataset.tab;
                    const badge = tab.querySelector('.badge');
                    if (type === 'all') {
                        badge.textContent = counts.unread;
                        badge.style.display = counts.unread > 0 ? 'inline-flex' : 'none';
                    } else {
                        badge.textContent = counts[type] || 0;
                        badge.style.display = (counts[type] || 0) > 0 ? 'inline-flex' : 'none';
                    }
                });
            }

            function showMessageDetail(message) {
                selectedMessageId = message.id;
                detailTitle.textContent = message.title;
                detailTime.textContent = formatTime(message.time);
                
                currentConversation = [
                    { 
                        type: 'received',
                        content: message.content,
                        time: message.time
                    },
                    ...message.replies.map(reply => ({
                        type: reply.sender === 'seller' ? 'sent' : 'received',
                        content: reply.content,
                        time: reply.time
                    }))
                ];

                renderConversation();
                messageDetailModal.style.display = 'flex';
                
                setTimeout(() => {
                    const modalContent = document.querySelector('.message-detail-content');
                    const navBarHeight = document.querySelector('.nav-bar').offsetHeight;
                    modalContent.style.maxHeight = `${window.innerHeight - navBarHeight - 30}px`;
                }, 100);
            }

            function renderConversation() {
                messageBubbleContainer.innerHTML = '';

                currentConversation.forEach((msg, index) => {
                    const bubble = document.createElement('div');
                    bubble.className = `message-bubble ${msg.type === 'sent' ? 'sent' : 'received'}`;
                    bubble.innerHTML = `
                        ${msg.content}
                        <div class="message-time-small">${formatTime(msg.time, true)}</div>
                    `;

                    messageBubbleContainer.appendChild(bubble);
                });

                messageBubbleContainer.scrollTop = messageBubbleContainer.scrollHeight;
            }

            function sendReply() {
                const content = replyInput.value.trim();
                if (!content) return;

                const currentMessage = messages.find(msg => msg.id === selectedMessageId);
                if (currentMessage) {
                    currentMessage.replies.push({
                        sender: 'user',
                        content: content,
                        time: new Date().toISOString()
                    });

                    currentConversation.push({
                        type: 'sent',
                        content: content,
                        time: new Date().toISOString()
                    });

                    renderConversation();
                    replyInput.value = '';
                }
            }

            function switchTab(tabElement) {
                tabs.forEach(tab => tab.classList.remove('active'));
                messageLists.forEach(list => list.classList.remove('active'));

                tabElement.classList.add('active');
                const tabId = tabElement.dataset.tab;
                document.getElementById(`${tabId}-messages`).classList.add('active');
            }

            tabs.forEach(tab => {
                tab.addEventListener('click', function() {
                    switchTab(this);
                });
            });

            closeDetailModal.addEventListener('click', function() {
                messageDetailModal.style.display = 'none';
            });

            window.addEventListener('click', function(event) {
                if (event.target === messageDetailModal) {
                    messageDetailModal.style.display = 'none';
                }
            });

            replyInput.addEventListener('keyup', function(event) {
                if (event.key === 'Enter' && !event.shiftKey) {
                    event.preventDefault();
                    sendReply();
                }
            });

            sendBtn.addEventListener('click', sendReply);

            initMessages();
            switchTab(document.querySelector('.message-tab.active'));
        });
        document.addEventListener('DOMContentLoaded', function () {
            const currentUser = JSON.parse(localStorage.getItem('currentUser'));
            if (!currentUser) {
                window.location.href = 'login.html';
            }
            // 原有的首页初始化逻辑
        });
    </script>
</body>
</html>